<?php

namespace App\Api\Controller;

use App\Http\Controllers\Controller;
use App\Models\Greeting;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class GreetingController extends BaseController
{
    public function index(Request $request)
    {
        $sort_info = $request->get('sort');
        $sort_info = json_decode($sort_info,true);
        $sort_field = $sort_info['name'] ?? 'sort';
        if (!in_array($sort_field,['created_at','sort','copy_count'])) {
            $sort_field = 'sort';
        }

        $category_id = (int)$request->get('category_id');
        $page_size = 10;

        $rows = Greeting::query()
            ->selectRaw('id,category_id,content,copy_count')
            ->where('category_id','=',$category_id)
            ->orderByDesc($sort_field)
            ->simplePaginate($page_size)
            ->toArray();

        return $this->sendData($rows);
    }

    public function show($id)
    {
        $id = (int)$id;
        $row = Greeting::find($id);

        $data = [
            'id' => $row->id,
            'content' => $row->content,
            'category_id' => $row->category_id,
            'category_title' => $row->category->title,
            'copy_count' => $row->copy_count,
        ];

        return $this->sendData($data);
    }

    public function search(Request $request)
    {
        $keyword = htmlspecialchars($request->get('keyword'));
        $page_size = 30;
        $rows = Greeting::query()
            ->selectRaw('id,category_id,content,copy_count')
            ->where('content','like',"%{$keyword}%")
            ->orWhereHas('category',function (Builder $query) use ($keyword) {
                $query->where('title','like',"%{$keyword}%");
            })
            ->orderBy('sort')
            ->simplePaginate($page_size)
            ->toArray();

        return $this->sendData($rows);
    }

    public function copy($id)
    {
        $id = (int)$id;
        $row = Greeting::find($id);

        $row->copy_count++;
        $row->save();

        return $this->sendData();
    }
}
